<?php
header('Content-type: text/plain');

require_once('frontstart.inc.php');   # defines: $options[], $context

class Application {
    function handle_request ($options) {
        try {
            global $debug_sql, $trace;
            $context   = App::context($options);
            $authdb     = $context->authdb();
            $group_id  = $context->getAuthenticatedGroupId();
            $neat      = (isset($_REQUEST['neat']) && $_REQUEST['neat']) ? 1 : 0;
            $debug_sql = (isset($_REQUEST['debug_sql']) && $_REQUEST['debug_sql']) ? $_REQUEST['debug_sql'] : 0;
            $tree      = Array();
            $matches   = Array();
            $get_root_node = 0;

            if (isset($_REQUEST['mode'])) {
                $mode = $_REQUEST['mode'];  # e.g. "getTree"
                if ($mode == 'getTree') {
                    if (isset($_REQUEST['node']) &&
                        isset($_REQUEST['id'])) {
                        $node = $_REQUEST['node'];
                        $id   = $_REQUEST['id'];
                        #echo "node=[$node] mode=[$mode] id=[$id]\n";
                        if ($node == 'src' && $id == 'src') {
                            $get_root_node = 1;
                        }
                        elseif (preg_match('/^([a-zA-Z0-9_]+)$/', $node, $matches)) {
                            $database = $matches[1];
                            $db = $context->database($database);
                            $schemas = $db->get_schema_names();
                            $database_children = Array();
                            foreach ($schemas as $schema) {
                                $database_children[] = Array('id'=>"$database.$schema", 'text'=>$schema, 'expanded'=>false);
                            }
                            $tree['success'] = true;
                            $tree['children'] = $database_children;
                        }
                        elseif (preg_match('/^([a-zA-Z0-9_]+)\\.([a-zA-Z0-9_]+)$/', $node, $matches)) {
                            $database = $matches[1];
                            $schema   = $matches[2];
                            $rows     = $authdb->get_rows('select t.table_name, t.table_label from db inner join db_schema s on s.db_id = db.db_id inner join db_table t on t.schema_id = s.schema_id where db.owner_group_id = ? and db.db_name = ? and s.owner_group_id = ? and s.schema_name = ?', array($group_id, $database, $group_id, $schema));
                            $schema_children = Array();
                            foreach ($rows as $row) {
                                #echo "table=[$table]\n";
                                $schema_children[] = Array('id'=>"$database.$schema.$row[0]", 'text'=>$row[1], 'expanded'=>false, 'view'=>true);
                            }
                            $tree['success'] = true;
                            $tree['children'] = $schema_children;
                        }
                        elseif (preg_match('/^([a-zA-Z0-9_]+)\\.([a-zA-Z0-9_]+)\\.([a-zA-Z0-9_]+)$/', $node, $matches)) {
                            $database = $matches[1];
                            $schema   = $matches[2];
                            $table    = $matches[3];
                            $rows = $authdb->get_rows("select apps.store_key, apps.content_str from app_store apps where apps.store_type = 'grid' and apps.owner_group_id = ? and apps.store_key like ?", array($group_id, "$database.$schema.$table.%"));
                            $schema_children = Array();
                            foreach ($rows as $row) {
                                list($fullview, $label) = $row;
                                if (!$label) {
                                    if (preg_match("/^$database\\.$schema\\.$table\\.(.+)$/", $fullview, $matches)) {
                                        $label = $matches[1];
                                    }
                                    else {
                                        $label = $fullview;
                                    }
                                }
                                #echo "table=[$table]\n";
                                $schema_children[] = Array('id'=>$fullview, 'text'=>$label, 'leaf'=>true, 'view'=>true);
                            }
                            $tree['success'] = true;
                            $tree['children'] = $schema_children;
                        }
                        else {
                            throw new \Exception("ERROR: unrecognized node in tree [$node]");
                        }
                    }
                    else {
                        throw new \Exception("ERROR: node and id must both be set");
                    }
                }
                else {
                    throw new \Exception("ERROR: unrecognized mode on tree [$mode]");
                }
            }
            if ($get_root_node) {
                $full = (isset($_REQUEST['full']) && $_REQUEST['full']) ? 1 : 0;
                $databases = $authdb->get_column('select db_name from db where owner_group_id = ? order by db_name', array($group_id));
                foreach ($databases as $database) {
                    if ($full) {
                        $database_children = Array();
                        $db = $context->database($database);
                        $schemas = $db->get_schema_names();
                        foreach ($schemas as $schema) {
                            #echo "schema=[$schema]\n";
                            $schema_children = Array();
                            $tables = $db->get_table_names($schema);
                            foreach ($tables as $table) {
                                #echo "table=[$table]\n";
                                $table_def = $db->get_table_def($table, $schema);
                                $schema_children[] = Array('id'=>"$database.$schema.$table", 'text'=>$table_def['label'], 'leaf'=>true);
                            }
                            $database_children[] = Array('id'=>"$database.$schema", 'text'=>$schema, 'expanded'=>false, 'children'=>$schema_children);
                        }
                        $tree[] = Array('id'=>$database, 'text'=>$database, 'expanded'=>false, 'children'=>$database_children);
                    }
                    else {
                        $tree[] = Array('id'=>$database, 'text'=>$database, 'expanded'=>false);
                    }
                }
            }

            $json = json_encode($tree);
            if ($neat) {
                $json = preg_replace('/\\},\\{/', "},\n {", $json);
                $json = preg_replace('/\\],\\[/', "],\n [", $json);
                $json = preg_replace('/\\[\\{/', "[\n {", $json);
                $json = preg_replace('/\\}\\]/', "}\n ]", $json);
            }
            echo $json . "\n";
        }
        catch (Exception $e) {
            $this->return_json_error($e->getMessage());
        }
        return(null);
    }

    function return_json_error ($message) {
        if (preg_match("/\n/",$message)) {
            $message = preg_replace("/ *\n */"," ",$message);
        }
        if (preg_match("/\\'/",$message)) {
            $message = preg_replace("/\\'/","\\'",$message);
        }
        echo "{\n";
        echo "    'success': false,\n";
        echo "    'msg': '$message'\n";
        echo "}\n";
    }
}

$application = new Application();
$application->handle_request($options);

